package com.shou.trigger.job;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.shou.domain.common.PageQueryEntity;
import com.shou.domain.park.model.ParkingSpaceEntity;
import com.shou.domain.park.service.IParkingSpaceService;
import com.shou.domain.reserve.service.IReservationService;
import com.shou.types.utils.TimeUtil;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * ClassName:ReservationJobHandler
 * Project:SmartPark
 * Package: com.shou.trigger.job
 * Description
 *
 * @Author Nemo
 * @Create 2025/2/22 23:32
 * @Version 1.0
 */

@Component
public class ReservationJobHandler {
    @Resource
    private IReservationService reservationService;
    @Resource
    private IParkingSpaceService parkingSpaceService;
    private final String CRON = "0 0 */2 * * ?";
    private XxlJobUtil xxlJobUtil = new XxlJobUtil();

    @XxlJob("resetReservation")
    public ReturnT<String> resetReservation() {
        String paramStr = XxlJobHelper.getJobParam();
        String[] methodParams = paramStr.split(",");
        // 删除预定记录
        reservationService.deleteByIds(List.of(Integer.parseInt(methodParams[2])));
        PageQueryEntity pageQueryEntity = PageQueryEntity.builder()
                .pageIndex(1)
                .pageSize(10)
                .lotCode(methodParams[0])
                .parkingSpaceCode(methodParams[1])
                .build();
        IPage<ParkingSpaceEntity> page = parkingSpaceService.pageQuery(pageQueryEntity);
        page.getRecords().get(0).setIsAvailable(1);
        page.getRecords().get(0).setUserId(null);
        // 修改车位状态，清空预定用户ID
        parkingSpaceService.updateParkingSpaceById(page.getRecords().get(0));
        // 删除动态任务
        removeDynamicJob(Integer.parseInt(methodParams[3]));
        return ReturnT.SUCCESS;
    }


    // 动态添加任务
    public void addDynamicJob(String handler, String params, String cron) {
        XxlJobInfo jobInfo = new XxlJobInfo();
        jobInfo.setJobDesc("1");
        jobInfo.setAuthor("负责人qyt");
        jobInfo.setAlarmEmail("1");
        jobInfo.setScheduleType("CRON");
        jobInfo.setScheduleConf(cron);
        jobInfo.setMisfireStrategy("DO_NOTHING");
        jobInfo.setExecutorRouteStrategy("FIRST");
        jobInfo.setExecutorHandler(handler);
        jobInfo.setExecutorParam(params);
        jobInfo.setExecutorBlockStrategy("DISCARD_LATER");
        jobInfo.setExecutorTimeout(0);
        jobInfo.setExecutorFailRetryCount(0);
        jobInfo.setGlueType("BEAN");
        jobInfo.setGlueSource("");
        jobInfo.setGlueRemark("GLUE代码初始化");
        jobInfo.setUpdateTime(null);
        jobInfo.setChildJobId("");
        jobInfo.setTriggerStatus(0);
        jobInfo.setTriggerLastTime(0);
        jobInfo.setTriggerNextTime(0);

        String addResult = xxlJobUtil.add(jobInfo);
        System.out.println("动态任务添加：" + addResult);
        ObjectMapper objectMapper = new ObjectMapper();

        try {
            JsonNode jsonNode = objectMapper.readTree(addResult);
            String contentValue = jsonNode.get("content").asText();
            // 将当前jobID保存到xxl-job任务的执行参数中，以便后续删除使用
            updateDynamicJob(Integer.parseInt(contentValue), params + "," + contentValue, jobInfo);
            // 启动刚已添加好的定时任务
            startDynamicJob(Integer.parseInt(contentValue));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    // 动态启动任务
    public void updateDynamicJob(Integer jobId, String paramStr, XxlJobInfo jobInfo) {
        jobInfo.setId(jobId);
        jobInfo.setExecutorParam(paramStr);
        jobInfo.setJobDesc("已做好删除准备的预定“取消”任务");

        String updateResult = xxlJobUtil.update(jobInfo);
        System.out.println("动态任务修改：" + updateResult + "参数：" + paramStr);
    }

    // 动态启动任务
    public void startDynamicJob(int jobId) {
        String startResult = xxlJobUtil.start(jobId);
        System.out.println("动态任务启动：" + startResult + "jobId:" + jobId);
    }

    // 动态删除任务
    public void removeDynamicJob(int jobId) {
        String removeResult = xxlJobUtil.remove(jobId);
        System.out.println("动态任务删除：" + removeResult + "jobId:" + jobId);
    }

    public static void main(String[] args) {
        ReservationJobHandler reservationJobHandler = new ReservationJobHandler();
//        reservationJobHandler.addDynamicJob("resetReservation", "1,1,1");
//        reservationJobHandler.removeDynamicJob(17);
//        LocalDateTime endTime = LocalDateTime.now().plusHours(2);
//        System.out.println(TimeUtil.getTimeCron(endTime));


//        reservationJobHandler.startDynamicJob(27);
    }
}
